﻿using System;
using hMailServer;

namespace hEmailDll
{
    public class EmailClass
    {
        private const string USERNAME = "Administrator";
        private const string PASSWORD = "123580.tom";

        // 创建邮箱账号
        public string addUser(string email, string domains)
        {
            try
            {
                email = email + domains;
                Application mailserver = new Application();
                //admin登录验证
                mailserver.Authenticate(USERNAME, PASSWORD);
                // 获取*.com 域
                var domain = mailserver.Domains.ItemByName[domains.Substring(1, domains.Length - 1)];
                var obAccounts = domain.Accounts;
                var obNewAccount = obAccounts.Add();
                obNewAccount.Address = email;
                obNewAccount.Password = PASSWORD;
                obNewAccount.Active = true;
                obNewAccount.MaxSize = 0;
                obNewAccount.Save();
                return "Success";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        // 删除邮箱账号
        public string delUser(string email, string domains)
        {
            try
            {
                email = email + domains;
                Application mailserver = new Application();
                //admin登录验证
                mailserver.Authenticate(USERNAME, PASSWORD);
                // 获取*.com 域
                var domain = mailserver.Domains.ItemByName[domains.Substring(1, domains.Length - 1)];
                var obAccounts = domain.Accounts;
                var obDelAccount = obAccounts.ItemByAddress[email];
                obDelAccount.Delete();
                return "Success";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        // 获取邮箱所有域名
        public string getUrl()
        {
            try
            {
                string str = "";
                Application mailserver = new Application();
                mailserver.Authenticate(USERNAME, PASSWORD);
                var domain = mailserver.Domains;
                for (var i = 1; i <= domain.Count; i++)
                {
                    str = str + "," + domain.ItemByDBID[i].Name;
                }
                return "Success" + str;
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
